import xmindparser
import argparse

def xmind_to_md(xmind_file, md_file):
    try:
        # 解析XMind文件
        content = xmindparser.xmind_to_dict(xmind_file)

        # 递归处理节点
        def parse_topic(topic, level=1, md_content=None):
            if md_content is None:
                md_content = []
                
            title = topic.get('title', '')
            notes = topic.get('note', '')
            
            # 获取子节点，检查两种可能的键名
            children = topic.get('topics', [])
            if not children and 'children' in topic:  # 某些XMind文件可能使用'children'键
                children = topic.get('children', [])

            # 添加换行确保格式正确
            if level <= 3:
                md_content.append(f"{'#' * level} {title}")
            else:
                indent = "  " * (level - 4)
                md_content.append(f"{indent}- {title}")
            
            # 确保标题和注释之间有适当的空行
            if notes:
                if level <= 3:
                    md_content.append("")
                    md_content.append(f"> {notes}")
                    md_content.append("")
                else:
                    indent = "  " * (level - 4)
                    md_content.append(f"{indent}  > {notes}")

            # 递归处理子节点
            if level < 8 and children:
                for child in children:
                    parse_topic(child, level + 1, md_content)
            
            return md_content

        # 生成Markdown内容
        with open(md_file, 'w', encoding='utf-8') as f:
            for sheet in content:
                # 为每个新的sheet创建新的列表
                md_lines = parse_topic(sheet['topic'])
                # 优化换行处理
                content = "\n".join(md_lines)
                # 移除多余的空行但保留格式
                content = "\n".join(line for line in content.split("\n") if line.strip() or line.startswith("  "))
                f.write(content + "\n\n")

        print(f"Successfully converted {xmind_file} to {md_file}")

    except Exception as e:
        print(f"Error: {str(e)}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Convert XMind to Markdown')
    parser.add_argument('input', help='Input XMind file path')
    parser.add_argument('output', help='Output Markdown file path')
    args = parser.parse_args()

    # 执行命令python xmind_to_md.py "D:\\IOT3.0\\2025.02\\CCS船级社二期\\一码通系统二期测试用例.xmind" "D:\\IOT3.0\\2025.02\\CCS船级社二期\\一码通系统二期测试用例.md"
    xmind_to_md(args.input, args.output)